function y_sub = polysub(y_data, poly_order);

% POLYSUB - subtract a polynomial fit of the data
%
%    YS = POLYSUB(Y, N) subtracts an Nth-order polynomial fit of the
%    rows in Y from Y and stores the result in YS.

% By:   S.C. Molitor (smolitor@med.unc.edu)
% Date: August 9, 2000

% initialize output

y_sub = [];

% validate input arguments

if (nargin ~= 2)
   msgbox('Invalid number of arguments', 'POLYSUB Error', 'warn');
   return
elseif (~isnumeric(y_data) | isempty(y_data))
   msgbox('Y must be a numeric array', 'POLYSUB Error', 'warn');
   return
elseif (~isscalar(poly_order))
   msgbox('N must be a scalar', 'POLYSUB Error', 'warn');
   return
elseif ((poly_order < 1) | (poly_order > 9))
   y_sub = y_data;
   return
end

x_data = [1 : size(y_data, 2)];
y_sub = y_data;
for i = 1 : size(y_data, 1)
   p = polyfit(x_data, y_data(i, :), poly_order);
   y_sub(i, :) = y_sub(i, :) - polyval(p, x_data);
end
return
